import Vue from 'vue'
import router from '@/router'
import store from '@/store'

/**
 * 获取uuid
 */
export function getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth (key) {
  return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  console.log(temp)
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

/**
 * 清除登录信息
 */
export function clearLoginInfo () {
  Vue.cookie.delete('token')
  store.commit('resetStore')
  router.options.isAddDynamicMenuRoutes = false
}

export function dateFormat (row, column) {
  if (column.property == 'createTime') {
    return row.createTime ? formatDate(new Date(row.createTime)) : ''
  }
  if (column.property == 'updateTime') {
    return row.updateTime ? formatDate(new Date(row.updateTime)) : ''
  }
}

export function getCookie() {
  return Vue.cookie.get('token')
}

//格式化时间
function formatDate(now) {
  var year = now.getFullYear(),
      month = now.getMonth() + 1 >= 10 ? now.getMonth() + 1 : '0' + (now.getMonth() + 1),
      date = now.getDate() >= 10 ? now.getDate() : '0' + now.getDate(),
      hour = now.getHours() >= 10 ? now.getHours() : '0' + now.getHours(),
      minute = now.getMinutes() >= 10 ? now.getMinutes() : '0' + now.getMinutes(),
      second = now.getSeconds() >= 10 ? now.getSeconds() : '0' + now.getSeconds();
  return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
}